<?php

/**
 * 阿里房源同步
 */

namespace app\crontab\controller\always;


use app\crontab\model\House2;
use custom\Log;
use custom\Mongo;
use custom\Redis;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

class HouseAli2 extends Command {

    public static $tableName = 'v2_house_ali';
    public static $sourceType = 2;
    public static $redisKey = 'v2_house_ali';

    protected function configure() {
        $this->setName('HouseAli2');
    }

    protected function execute(Input $input, Output $output) {
        $this->initial();
    }

    public function initial() {
        echo "start\n";
        $redisModel = Redis::getInstance();
        $errNum = 0;//错误次数
        $wait = 0;//等待次数
        //分页查询
        $utime = $redisModel->get(self::$redisKey);
        if ($utime === false) $utime = 0;
        $filter = [
            'utime' => ['$gte' => (string)$utime],
            'city'  => ['$ne' => '呼和浩特'],
        ];
        $long = 500;//每页处理条数
        $initNum = 0;
        $config = config('db.mongo2');
        Mongo::setOption($config);
        $mongo = Mongo::getInstance();
        while (true) :
            $options = [
                'skip'  => $initNum,
                'limit' => $long,
                'sort'  => [
                    'utime' => 1
                ]
            ];
            $cursor = $mongo->select(self::$tableName, $filter, $options);
            $datas = (array)$cursor;
//            print_r($datas);die;
            //逐条处理
            if (!empty($cursor)) House2::doOne($datas, self::$redisKey, $errNum, self::$sourceType);
            $len = count($datas);
            $initNum += $len;
            if ($len < $long) {
                if ($wait >= 6) break;
                echo "waiting...\n";
                sleep(300);
                $wait++;
                continue;
            }
        endwhile;
        echo "end\n";
        Log::write('total->' . $initNum, self::$tableName . "_Ret.log");
    }
}
